import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/exam/ExamPartPage.dart';
import 'package:ichinesereader/exam/ExamQuestionIndexPage.dart';
import 'package:ichinesereader/exam/util/ExamLayoutUtil.dart';
import 'controllers/ExamPageController.dart';

// ignore: must_be_immutable
class ExamPage extends GetView<ExamPageController> {
  ExamPage({Key? key}) : super(key: key);
  String? assessmentId = Get.arguments['id'];
  String? dataJson = Get.arguments['dataJson'];
  String title = 'Assessment';
  var textStylePartTitle = TextStyle(fontWeight: FontWeight.normal, color: (Get.isDarkMode ? Color(0xFF757575) : Colors.black87), fontSize: 20);
  var textStyleSectionTitle = const TextStyle(fontWeight: FontWeight.normal, color: Colors.blue, fontSize: 18);
  var textStyleQuestionTitle = const TextStyle(fontWeight: FontWeight.normal, color: Colors.grey, fontSize: 16);

  @override
  Widget build(BuildContext context) {
    Log.debug('ExamPage build');
    delayedLoadData();
    return Scaffold(
        appBar: AppBar(
          title: Text(title),
          centerTitle: true,
        ),
        body: WillPopScope(
            onWillPop: () async {
              controller.reportCurrentPageRecord();
              return true;
            },
            child: _buildExam()));
  }

  void delayedLoadData() {
    Future.delayed(const Duration(milliseconds: 10), () {
      loadData();
    });
  }

  void loadData() {
    Log.debug('ExamPage loadData');
    controller.loadData(assessmentId!);
  }

  Widget _buildExam() {
    Log.debug('ExamPage _buildExam');

    return Container(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          children: [_buildExamTop(), _buildExamMain(), _buildExamBottom()],
        ));
  }

  Widget _buildExamTop() {
    return Obx(() {
      Log.debug('ExamPage _buildExamTop');
      // ignore: unused_local_variable
      var currentQuestionStepIndex = controller.currentQuestionStepIndex.value; //起到订阅作用
      var questionIndexTitle = Row(children: []);

      if (controller.currentUiPartIndex != null) {
        // Part1 >
        if (controller.assessmentResult!.list!.length > 1) {
          questionIndexTitle.children.add(Text('${controller.currentUiPartIndex?.name} > ', style: textStylePartTitle));
        }
      }
      if (controller.currentQuestionStep?.stepType == UiQuestionStep.STEPTYPE_QUESTION) {
        // Q1 >
        questionIndexTitle.children.add(Text('${controller.currentUiSectionIndex?.name} > ', style: textStyleSectionTitle));
        // Question 1 of 15  Step=1
        questionIndexTitle.children.add(Text(
            ' Question ${(controller.currentQuestionStep?.questionIndex ?? 0) + 1} of ${controller.currentUiSectionIndex?.questionIndexList?.length}'));
      }

      return Row(
        children: [
          questionIndexTitle,
          const Expanded(child: SizedBox()),
          OutlinedButton(
              onPressed: () async {
                showGeneralDialog(
                    context: Get.context!,
                    transitionDuration: const Duration(milliseconds: 400),
                    pageBuilder: (bc, ania, anis) {
                      // 索引页面
                      return ExamQuestionIndexPage();
                    });
              },
              child: const Text('INDEX'))
        ],
      );
    });
  }

  Widget _buildExamMain() {
    Log.debug('ExamPage _buildExamMain');
    Widget? examMain;
    examMain = const ExamPartPage();

    var childExpanded = Container(
      padding: const EdgeInsets.only(left: 10, top: 10, right: 10, bottom: 10),
      child: examMain,
    );
    var borderContainer = Container(
      decoration: ExamLayoutUtil.getBoxDecoration(),
      width: double.infinity,
      child: childExpanded, //代表百分百宽度
    );
    return Expanded(child: borderContainer);
  }

  Widget _buildExamBottom() {
    void _onPrevPage() async {
      controller.prevPage();
    }

    void _onNextPage() async {
      controller.nextPage();
    }

    void _onSubmitAction() async {
      List numList = controller.verifyCompleteAllQuestion();
      if (numList.isEmpty) {
        controller.submitAction();
      } else {
        showQuestionDialog(Get.context!, numList);
      }
    }

    return Obx(() {
      Log.debug('ExamPage _buildExamBottom');
      return Row(
        children: [
          // Text('${stepIndex}'),
          const Expanded(child: SizedBox()),
          Row(
            children: [
              OutlinedButton(onPressed: controller.isPrevPageEnable.value ? _onPrevPage : null, child: const Text('PREV')),
              const SizedBox(width: 10),
              OutlinedButton(
                  onPressed: controller.isNextPageEnable.value ? _onNextPage : _onSubmitAction,
                  child: controller.isNextPageEnable.value ? const Text('NEXT') : const Text('SUBMIT'))
            ],
          ),
        ],
      );
    });
  }

  void showQuestionDialog(BuildContext context, List list) async {
    await showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
            title: Text('Are you sure you want to submit?',
                textAlign: TextAlign.center, style: TextStyle(color: Color(0xff3d6f8c), fontSize: 22, fontWeight: FontWeight.w500)),
            content: SizedBox(
                width: 350,
                height: list.isEmpty ? 10 : 200,
                child: list.isEmpty
                    ? SizedBox()
                    : Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                        Text('Undone Index:', style: TextStyle(color: Get.isDarkMode ? Colors.white : Colors.red, fontSize: 18)),
                        SizedBox(height: 10),
                        Expanded(
                            child: Scrollbar(
                                thumbVisibility: true,
                                child: SingleChildScrollView(
                                    primary: true,
                                    child: Text(list.toString(),
                                        style: TextStyle(color: Get.isDarkMode ? Colors.white60 : Color(0xFF212529), fontSize: 16, height: 1.5)))))
                      ])),
            shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10.0))),
            contentPadding: const EdgeInsets.fromLTRB(24, 15, 24, 30),
            actions: <Widget>[
              TextButton(
                  child: Text('Cancel', style: TextStyle(color: Colors.grey, fontSize: 16)),
                  onPressed: () {
                    Get.back();
                  }),
              TextButton(
                  child: Text('Submit', style: TextStyle(fontSize: 16)),
                  onPressed: () {
                    Get.back();
                    controller.submitAction();
                  })
            ]);
      },
    );
  }
}
